//
//  DeviceSettingViewController.m
//  upnpxdemo
//
//  Created by a  on 13-8-26.
//  Copyright (c) 2013年 wiimu.inc. All rights reserved.
//

#import "WlanSelectViewController.h"
#import "MJRefresh.h"
#import "MMProgressHUD.h"

@interface WlanSelectViewController ()
<MJRefreshBaseViewDelegate>
{
    MJRefreshHeaderView *_header;
    
    NSArray * wlanArr;
    
    NSTimer * getInternetStatusTimer;
    NSTimer * connectStatusTimer;
    
    NSString * currentConnectedDevice;
//    int connectTimeCount;//用于在硬件发生错误时处理；10s超时，报错，不再连接。
    
    BOOL isInternetConnected;
}

@property (retain) NSArray * wlanArr;
@property (retain) NSString * currentConnectedDevice;
@property (assign) IBOutlet UILabel * infoLabel;
@property (assign) IBOutlet UITableView * wlanTable;

@end

@implementation WlanSelectViewController
@synthesize wlanArr;
@synthesize currentConnectedDevice;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        isInternetConnected = NO;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    //mj
    _header = [MJRefreshHeaderView header];
    _header.scrollView = self.wlanTable;
    _header.delegate = self;
    
    
//    connectTimeCount = 0;
    
    [self prepareUI];
    
    [self getApList];
    [self getCurrentConnectedDevice];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)prepareUI
{

}

-(void)getApList
{    
    [[GlobalService sharedInstance] getWifiList:self];

    [MMProgressHUD showWithStatus:@"loading..."];
}

-(void)getCurrentConnectedDevice
{
    [[GlobalService sharedInstance] getCurrentConnectedDevice:self];
}

-(void)connectTo:(NSString *)ssid andAuth:(NSString *)auth andPass:(NSString *)password andChannel:(NSString *)channel andEncrypt:(NSString *)encrypt
{
//    connectTimeCount = 0;
    
    [MMProgressHUD showWithStatus:NSLocalizedString(@"CONNECTTOWIFIANDWAIT",@"")];
    
    [[GlobalService sharedInstance] connectToWifi:self withSsid:ssid andAuth:auth andPass:password andChannel:channel andEncrypt:encrypt];
}

-(NSString *)str2HexStr:(char*)str
{
    char chars[] = "0123456789ABCDEF";
    NSMutableString * sb = [NSMutableString string];
    int bit;
    for (int i = 0; i < strlen(str); i++)
    {
        bit = (str[i] & 0x0f0) >> 4;
        [sb appendFormat:@"%c",chars[bit]];
        bit = str[i] & 0x0f;
        [sb appendFormat:@"%c",chars[bit]];
    }
    return sb;
}

-(void)getInternetTimerMethod
{
    [[GlobalService sharedInstance] getDeviceInfo:self url:[GlobalInfo sharedInstance].currentBaseURL];
}

-(void)getConnectStatusTimerMethod
{
//    connectTimeCount++;
    
    [[GlobalService sharedInstance] getWifiConnectStatus:self];
}

-(void)connectionFaild
{
    [self stopAllTimers];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
}

-(void)stopAllTimers
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if(getInternetStatusTimer != nil && [getInternetStatusTimer isValid])
        {
            [getInternetStatusTimer invalidate];
            getInternetStatusTimer = nil;
        }
        if(connectStatusTimer != nil && [connectStatusTimer isValid])
        {
            [connectStatusTimer invalidate];
            connectStatusTimer = nil;
        }
    });
}

- (NSString *)tabImageName
{
	return @"TAB_ICON_5.png";
}

- (NSString *)tabTitle
{
	return NSLocalizedString(@"WIFICONFIGURE",@"");
}

#pragma mark - navigation methods
-(NSString *)navigationBarTitle
{
    return [[GlobalInfo sharedInstance].currentSelectedUpnPInfo objectForKey:@"ssid"];
}

-(BOOL)isNewVersionButtonEnabled
{
    return YES;
}

-(IBAction)backButtonPressed:(id)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
}

#pragma mark -
#pragma mark UITableView Delegate & Datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [wlanArr count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
    }
    else
    {
        for(UIView * subview in [cell.contentView subviews])
        {
            [subview removeFromSuperview];
        }
    }

    // Configure the cell.
    
    NSDictionary * dic = [wlanArr objectAtIndex:indexPath.row];
    NSString * authStr = [dic objectForKey:@"auth"];
    int dbm = [[dic objectForKey:@"rssi"] intValue];
    
    if(dbm >= 0 && dbm <= 20)
    {
        dbm = 0;
    }
    else if(dbm >= 21 && dbm <= 40)
    {
        dbm = 1;
    }
    else if(dbm >= 41 && dbm <= 60)
    {
        dbm = 2;
    }
    else if(dbm >= 61 && dbm <= 80)
    {
        dbm = 3;
    }
    else if(dbm >= 81 && dbm <= 100)
    {
        dbm = 4;
    }
    
    UIImage * image = nil;
    NSString * imageName = nil;
    if([authStr isEqualToString:@"OPEN"])
    {
        imageName = [NSString stringWithFormat:@"wifi_nlock%d.png",dbm];
    }
    else
    {
        imageName = [NSString stringWithFormat:@"wifi_lock%d.png",dbm];
    }
    
    image = [UIImage imageNamed:imageName];
    
    UIImageView * imageview = [[UIImageView alloc] initWithImage:image];
    [cell.contentView addSubview:imageview];
    [imageview setFrame:CGRectMake(10, 10, 40, 40)];
    
    UILabel * label = [[UILabel alloc] init];
    label.frame = CGRectMake(60, 10, 200, 40);
    label.backgroundColor = [UIColor clearColor];
    [cell.contentView addSubview:label];
    label.text = [dic objectForKey:@"ssid"];
    
    UIImageView * rightImage = nil;
    
    if([currentConnectedDevice isEqualToString:[dic objectForKey:@"ssid"]])
    {
        rightImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"chosen.png"]];
        rightImage.frame = CGRectMake(tableView.frame.size.width-50, 18, 30, 30);
    }
    else
    {
        rightImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"rightarrow1.png"]];
        rightImage.frame = CGRectMake(tableView.frame.size.width-40, 20, 10, 20);
    }
    
    
    [cell.contentView addSubview:rightImage];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
    
    NSDictionary * dic = [wlanArr objectAtIndex:indexPath.row];
    NSString * authStr = [dic objectForKey:@"auth"];
    
    if([authStr isEqualToString:@"OPEN"])
    {
        [self connectTo:[dic objectForKey:@"ssid"] andAuth:[dic objectForKey:@"auth"] andPass:@":NONE" andChannel:[dic objectForKey:@"channel"] andEncrypt:[dic objectForKey:@"encry"]];
    }
    else//输入密码
    {
        NSString * iosStr = nil;
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
            iosStr = @"PasswordInputView";
        } else {
            iosStr = @"PasswordInputView_iPad";
        }
        
        PasswordInputView * piv = [[[NSBundle mainBundle] loadNibNamed:iosStr owner:self options:nil] lastObject];
        piv.ssid = [dic objectForKey:@"ssid"];
        piv.auth = [dic objectForKey:@"auth"];
        piv.channel = [dic objectForKey:@"channel"];
        piv.encry = [dic objectForKey:@"encry"];
        piv.delegate = self;
        [self.view addSubview:piv];
    }
}

#pragma mark -
#pragma mark servicecallbacks
-(void)serviceGetWifiListCallBack:(NSDictionary*)dicCallBack
{
    [MMProgressHUD dismiss];
    [_header endRefreshing];
    
    NSDictionary * dic = dicCallBack;
    
    if([[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        
        [self.view makeToast:NSLocalizedString(@"ALERT_GETWIFILISTFAILED",@"")
                    duration:3.0
                    position:@"bottom"
                       title:NSLocalizedString(@"ALERT_TITLE",@"")];
        return;
    }
    else if([[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    
    if(dic == nil)
    {
        [self.view makeToast:NSLocalizedString(@"ALERT_GETWIFILISTFAILED",@"")
                    duration:3.0
                    position:@"bottom"
                       title:NSLocalizedString(@"ALERT_TITLE",@"")];
        return;
    }
    
    NSMutableArray * arr = [NSMutableArray array];
    
    for(NSDictionary * wlanDic in [dic objectForKey:@"aplist"])
    {
        NSString * ssidStr = [wlanDic objectForKey:@"ssid"];
//        NSString * bssidStr = [wlanDic objectForKey:@"bssid"];
        
//        if(ssidStr != nil && [ssidStr length] != 0 && ( ![ssidStr hasPrefix:@"LinkPlay_"] && ![ssidStr hasPrefix:@"AllCast_"] && ![ssidStr hasPrefix:@"WIFIAudio_"] && ![ssidStr hasPrefix:@"WifiAudio_"] && ![ssidStr hasPrefix:@"WiFiAudio_"] && ![bssidStr hasPrefix:@"00226C"]))
//        {
//            [arr addObject:wlanDic];
//        }
//        if([ssidStr length] != 0 && ( ![ssidStr hasPrefix:@"LinkPlay_"] && ![ssidStr hasPrefix:@"AllCast_"]))
//        {
//            [arr addObject:wlanDic];
//        }
        if([ssidStr length] != 0 && ( ![ssidStr hasPrefix:@"LinkPlay_"] && ![ssidStr hasPrefix:@"AllCast_"]))
        {
            [arr addObject:wlanDic];
        }
    }
    
    self.wlanArr = arr;
    
    [_wlanTable reloadData];
}

-(void)serviceGetCurrentConnectedDeviceCallBack:(NSDictionary*)dicCallBack
{
    NSDictionary * dic = dicCallBack;
    
    if(dic == nil || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        
        
        return;
    }
    else if([[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    
    NSString * retstr = [dicCallBack objectForKey:@"responseString"];
    
    if(retstr == nil)
    {
        [self.view makeToast:NSLocalizedString(@"ALERT_GETCONNECTEDDEVICEFAILED",@"")
                    duration:3.0
                    position:@"bottom"
                       title:NSLocalizedString(@"ALERT_TITLE",@"")];
        return;
    }
    
    NSArray * array = [retstr componentsSeparatedByString:@":"];
    
    if([array count] == 2)//NULL
    {
        self.infoLabel.text = NSLocalizedString(@"UNCONNECTED",@"");
    }
    else if([array count] == 3)
    {
        if([[array objectAtIndex:2] intValue] == 1)
        {
            self.currentConnectedDevice = [array objectAtIndex:1];
            [_wlanTable reloadData];
            
            self.infoLabel.text = [NSString stringWithFormat:@"%@ %@  ",NSLocalizedString(@"CONNECTEDTO",@""),[array objectAtIndex:1]];
            
            if(![getInternetStatusTimer isValid])
            {
                //不停获取是否连接至internet
                getInternetStatusTimer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(getInternetTimerMethod) userInfo:nil repeats:YES];
                
                [[NSRunLoop currentRunLoop] addTimer:getInternetStatusTimer forMode:NSDefaultRunLoopMode];
            }
        }
        else
        {
            if([[array objectAtIndex:1] length] != 0)
            {
                self.infoLabel.text = [NSString stringWithFormat:@"%@ %@",NSLocalizedString(@"UNCONNECTEDTO",@""),[array objectAtIndex:1]];
            }
            else
            {
                self.infoLabel.text = NSLocalizedString(@"UNCONNECTED",@"");
            }
        }
    }
    else
    {
        self.infoLabel.text = NSLocalizedString(@"PARSEERROR",@"");
    }
}

-(void)serviceConnectToWifiCallBack:(NSDictionary*)dicCallBack
{
     NSDictionary * dic = dicCallBack;
    
    if(dic == nil || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        
        
        return;
    }
    else if([[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    
    if(![connectStatusTimer isValid] && [GlobalInfo sharedInstance].isDisconnect == NO)
    {
        [MMProgressHUD showWithStatus:@"loading..."];
        
        if(![connectStatusTimer isValid])
        {
            connectStatusTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(getConnectStatusTimerMethod) userInfo:nil repeats:YES];
            
            [[NSRunLoop currentRunLoop] addTimer:connectStatusTimer forMode:NSDefaultRunLoopMode];
        }
    }
}

//只为检测internet
-(void)serviceGetDeviceInfoCallBack:(NSDictionary*)dicCallBack
{
    NSDictionary * dic = dicCallBack;

    if(dic == nil || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        return;
    }
    else if([[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }

    NSString * str = nil;
    if([[dic objectForKey:@"internet"] intValue] == 1)
    {
        str = NSLocalizedString(@"CANVISITINTERNET",@"");
        if(isInternetConnected == NO)
        {
            //有网络 则开始检测是否有固件更新
            [[NSNotificationCenter defaultCenter] postNotificationName:@"BeginCheckUpdate" object:nil];
            
            isInternetConnected = YES;
        }
    }
    else
    {
        isInternetConnected = NO;
        str = NSLocalizedString(@"CANNOTVISITINTERNET",@"");
    }
    
    NSString * infoStr = _infoLabel.text;
    NSRange range = [infoStr rangeOfString:@"  " options:NSBackwardsSearch];
    if(range.location == NSNotFound)
    {
        _infoLabel.text = [infoStr stringByAppendingFormat:@"  %@",str];
    }
    else
    {
        infoStr = [infoStr substringToIndex:range.location];
        _infoLabel.text = [infoStr stringByAppendingFormat:@"  %@",str];
    }
}

-(void)serviceGetWifiConnectStatusCallBack:(NSDictionary*)dicCallBack
{
    NSDictionary * dic = dicCallBack;
    
    if(dic == nil || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_FAIL intValue])
    {
        
        
        return;
    }
    else if([[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_CONNECTIONFAIL intValue] || [[dic objectForKey:@"responsestatus"] intValue] == [SERVICE_TIMEOUT intValue])
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopTabBarController" object:self];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"ErrorComeBack" object:nil];
    }
    
    NSString * connectstate = [dicCallBack objectForKey:@"connectstate"];
    NSLog(@"connectstate %@",connectstate);
    if([connectstate isEqualToString:@"OK"])
    {
        [self.view makeToast:NSLocalizedString(@"ALERT_CONNECTWIFISUCCESS",@"")
                    duration:3.0
                    position:@"bottom"
                       title:NSLocalizedString(@"ALERT_TITLE",@"")];
        if(connectStatusTimer != nil && [connectStatusTimer isValid])
        {
            [connectStatusTimer invalidate];
            connectStatusTimer = nil;
        }

        [MMProgressHUD showWithStatus:NSLocalizedString(@"ALERT_CONNECTWIFISUCCESS",@"")];
        
        self.wlanArr = nil;
        [self.wlanTable reloadData];
        [self getApList];
        [self getCurrentConnectedDevice];
    }
    else if([connectstate isEqualToString:@"FAIL"]||[connectstate isEqualToString:@"NONE"])
    {
        [self.view makeToast:NSLocalizedString(@"ALERT_CONNECTWIFIFAILED",@"")
                    duration:3.0
                    position:@"bottom"
                       title:NSLocalizedString(@"ALERT_TITLE",@"")];
        if(connectStatusTimer != nil && [connectStatusTimer isValid])
        {
            [connectStatusTimer invalidate];
            connectStatusTimer = nil;
        }
        [MMProgressHUD dismiss];
        
        self.wlanArr = nil;
        [self.wlanTable reloadData];
        [self getApList];
        [self getCurrentConnectedDevice];
    }
    else if([connectstate isEqualToString:@"PAIRFAIL"])
    {
        [self.view makeToast:NSLocalizedString(@"ALERT_WRONGPASS",@"")
                    duration:3.0
                    position:@"bottom"
                       title:NSLocalizedString(@"ALERT_TITLE",@"")];
        if(connectStatusTimer != nil && [connectStatusTimer isValid])
        {
            [connectStatusTimer invalidate];
            connectStatusTimer = nil;
        }

        [MMProgressHUD dismiss];
        
        self.wlanArr = nil;
        [self.wlanTable reloadData];
        [self getApList];
        [self getCurrentConnectedDevice];
    }
//    else
//    {
//        if(connectTimeCount > 20)
//        {    
//            [self.view makeToast:NSLocalizedString(@"ALERT_CONNECTWIFIFAILED",@"")
//                        duration:3.0
//                        position:@"bottom"
//                           title:NSLocalizedString(@"ALERT_TITLE",@"")];
//            if(connectStatusTimer != nil && [connectStatusTimer isValid])
//            {
//                [connectStatusTimer invalidate];
//                connectStatusTimer = nil;
//            }
//
//            [MMProgressHUD dismiss];
//            
//            self.wlanArr = nil;
//            [self.wlanTable reloadData];
//            [self getApList];
//            [self getCurrentConnectedDevice];
//        }
//    }
}

#pragma mark -
#pragma mark PasswordInputDelegate
-(void)ConfirmButtonPressed:(NSDictionary *)infoDic
{
    [self connectTo:[infoDic objectForKey:@"ssid"] andAuth:[infoDic objectForKey:@"auth"] andPass:[infoDic objectForKey:@"password"] andChannel:[infoDic objectForKey:@"channel"] andEncrypt:[infoDic objectForKey:@"encry"]];
}

#pragma mark - MJRefreshBaseViewDelegate method
- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if(refreshView == _header)
    {
        self.wlanArr = nil;
        [_wlanTable reloadData];
        
        [self getApList];
    }
}
@end
